package mgorm

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/event"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"net"
	"strings"
	"time"
)

func NewMongoDb(config *MongoDbConfig) *mongo.Database {
	uri := fmt.Sprintf(
		"mongodb://%s:%s@%s/%s?authSource=%s&",
		config.User, config.Pass,
		strings.Join(config.Hosts, ","),
		config.Db, config.Auth)
	LogToConsole(uri)
	//事件监听输出日志
	m := new(event.CommandMonitor)
	m.Started = func(ctx context.Context, startedEvent *event.CommandStartedEvent) {
		if config.LogOn {
			LogToConsoleNoTrace(startedEvent.Command.String())
		}
		//dev.PrintDebugGo(startedEvent.Command.String())
	}
	m.Succeeded = func(ctx context.Context, succeededEvent *event.CommandSucceededEvent) {
		//dev.PrintDebugGo(succeededEvent.Duration)
		if config.LogOn {
			LogToConsoleNoTrace(fmt.Sprintf("耗时:%d ms", succeededEvent.Duration.Milliseconds()))
		}

	}
	m.Failed = func(ctx context.Context, failEvent *event.CommandFailedEvent) {
		if config.LogOn {
		}
	}
	dialer := &net.Dialer{
		KeepAlive: 30 * time.Second,
	}
	client, err := mongo.Connect(
		context.Background(),
		options.Client().
			ApplyURI(uri).
			SetMaxPoolSize(config.PoolSize).
			SetLocalThreshold(3*time.Second).
			SetMonitor(m).
			SetDialer(dialer).
			SetConnectTimeout(10*time.Second).
			SetServerSelectionTimeout(5*time.Second),
	)
	if err != nil {
		LogToConsole(fmt.Sprintf("初始化mongodb失败:[NewClient]%s", err.Error()))
	}
	ctxTimeout, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	err = client.Ping(ctxTimeout, nil)
	if err != nil {
		LogToConsole(fmt.Sprintf("初始化mongodb失败:[Ping]%s", err.Error()))
	}
	DBMongo := client.Database(config.Db)
	LogToConsoleNoTrace("MONGODB 初始化完成")
	return DBMongo
}
